<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import LoginModal from "@/components/LoginModal.vue";
import RegisterModal from "@/components/RegisterModal.vue";
import UserStatus from "@/components/UserStatus.vue";
import SearchBox from "@/components/SearchBox.vue";
import FamilyManagement from "@/components/FamilyManagement.vue";
import AccountingManagement from "@/components/accounting/AccountingManagement.vue";
import UnifiedFuelManagement from "@/components/fuel/UnifiedFuelManagement.vue";
import ScheduleManagement from "@/components/schedule/ScheduleManagement.vue";
import DesktopIcons from "@/components/DesktopIcons.vue";
import AppWindows from "@/components/AppWindows.vue";
import { useAuthStore } from "@/stores/auth";
import { useScheduleStore } from "@/stores/schedule";
import { useFamilyStore } from "@/stores/family";
import type { User } from "@/types/auth";
import type { App, ContextMenuItem } from "@/types/common";

// 右键菜单状态
const contextMenu = ref({
  visible: false,
  x: 0,
  y: 0,
  items: [] as ContextMenuItem[],
});

// 登录模态框状态
const loginModal = ref({
  visible: false,
});

// 注册模态框状态
const registerModal = ref({
  visible: false,
});

// 管理组件状态
const showFamilyManagement = ref(false);
const showAccountingManagement = ref(false);
const showScheduleManagement = ref(false);
const showUnifiedFuelManagement = ref(false);

// 应用窗口引用
const appWindowsRef = ref();

// 获取认证状态管理器
const authStore = useAuthStore();
const scheduleStore = useScheduleStore();
const familyStore = useFamilyStore();

// 响应式布局
const isMobile = ref(false);
const dialogWidth = computed(() => isMobile.value ? '95%' : '80%');

// 检查屏幕尺寸
const checkScreenSize = () => {
  isMobile.value = window.innerWidth < 768;
};

onMounted(() => {
  checkScreenSize();
  window.addEventListener('resize', checkScreenSize);
});

onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize);
});

// 右键菜单项
const getContextMenuItems = () => {
  const menuItems = [];

  // 如果用户未登录，显示登录选项
  if (!authStore.isAuthenticated) {
    menuItems.push({ id: 1, label: "登录", icon: "👤", disabled: false });
  } else {
    menuItems.push({ id: 2, label: "注销", icon: "🚪", disabled: false });
  }

  return menuItems;
};

// 处理键盘快捷键
const handleKeyDown = (event: KeyboardEvent) => {
  // ESC 关闭右键菜单或登录模态框
  if (event.key === "Escape") {
    if (contextMenu.value.visible) {
      hideContextMenu();
    } else if (loginModal.value.visible) {
      closeLoginModal();
    } else if (registerModal.value.visible) {
      closeRegisterModal();
    }
  }
};

// 登录相关功能
const openLoginModal = () => {
  loginModal.value.visible = true;
  hideContextMenu();
};

const closeLoginModal = () => {
  loginModal.value.visible = false;
};

const openRegisterModal = () => {
  registerModal.value.visible = true;
  loginModal.value.visible = false;
};

const closeRegisterModal = () => {
  registerModal.value.visible = false;
};

const handleLoginSuccess = (userData: User) => {
  console.log("登录成功:", userData);
  // 登录成功后重新初始化认证状态
  authStore.initAuth();
};

const handleRegisterSuccess = (userData: User) => {
  console.log("注册成功:", userData);
  // 注册成功后重新初始化认证状态
  authStore.initAuth();
};

const handleLogout = async () => {
  try {
    await authStore.logout();
    hideContextMenu();
    console.log("已注销");
  } catch (error) {
    console.error("注销失败:", error);
  }
};

// 处理右键菜单
const handleContextMenu = (event: MouseEvent) => {
  event.preventDefault();
  event.stopPropagation();

  // 隐藏已存在的菜单
  hideContextMenu();

  // 计算菜单位置，确保不超出屏幕边界
  const menuWidth = 220; // 菜单宽度
  const menuHeight = contextMenu.value.items.length * 36 + 16; // 估算菜单高度
  const margin = 10; // 边距

  let x = event.clientX;
  let y = event.clientY;

  // 防止菜单超出右边界
  if (x + menuWidth > window.innerWidth - margin) {
    x = window.innerWidth - menuWidth - margin;
  }

  // 防止菜单超出下边界
  if (y + menuHeight > window.innerHeight - margin) {
    y = window.innerHeight - menuHeight - margin;
  }

  // 确保菜单不超出左边界和上边界
  x = Math.max(margin, x);
  y = Math.max(margin, y);

  // 使用 setTimeout 确保 DOM 更新
  setTimeout(() => {
    contextMenu.value = {
      visible: true,
      x,
      y,
      items: getContextMenuItems(),
    };
  }, 0);
};

// 隐藏右键菜单
const hideContextMenu = () => {
  contextMenu.value.visible = false;
};

// 处理右键菜单项点击
const handleContextMenuItemClick = (item: ContextMenuItem) => {
  // 防止禁用项的点击
  if (item.disabled) {
    return;
  }

  hideContextMenu();

  switch (item.label) {
    case "登录":
      openLoginModal();
      break;
    case "注销":
      handleLogout();
      break;
    default:
      console.log("Action not implemented:", item.label);
  }
};

// 处理显示登录模态框事件
const handleShowLoginModal = () => {
  loginModal.value.visible = true;
};

// 处理认证要求事件（401错误时触发）
const handleAuthRequired = () => {
  console.log("认证失败，需要重新登录");
  loginModal.value.visible = true;
};

// 处理打开家庭成员管理事件（对话框方式）
const handleOpenFamilyManagement = () => {
  showFamilyManagement.value = true;
};

// 处理打开家庭成员管理窗口事件（AppWindow方式）
const handleOpenFamilyWindow = (event: Event) => {
  const app = (event as CustomEvent).detail;
  
  // 检查是否需要认证
  if (app.requiresAuth && !authStore.isAuthenticated) {
    openLoginModal();
    return;
  }

  // 通过AppWindows打开家庭成员管理
  if (appWindowsRef.value) {
    appWindowsRef.value.openFamilyManagement(app);
  }
};

// 处理打开记账管理事件
const handleOpenAccountingManagement = () => {
  showAccountingManagement.value = true;
};

// 处理打开日程管理事件
const handleOpenScheduleManagement = () => {
  showScheduleManagement.value = true;
};


// 处理桌面应用点击
const handleDesktopAppClick = (app: App) => {
  // 检查是否需要认证
  if (app.requiresAuth && !authStore.isAuthenticated) {
    openLoginModal();
    return;
  }

  // 打开对应的应用窗口
  switch (app.id) {
    case "family":
      if (appWindowsRef.value) {
        appWindowsRef.value.openFamilyManagement(app);
      }
      break;
    case "accounting":
      if (appWindowsRef.value) {
        appWindowsRef.value.openAccountingManagement(app);
      }
      break;
    case "schedule":
      if (appWindowsRef.value) {
        appWindowsRef.value.openScheduleManagement(app);
      }
      break;
    case "fuel-records":
      if (appWindowsRef.value) {
        appWindowsRef.value.openUnifiedFuelManagement(app);
      }
      break;
  }
};

// 关闭管理组件
const closeFamilyManagement = () => {
  showFamilyManagement.value = false;
};

const closeAccountingManagement = () => {
  showAccountingManagement.value = false;
};

const closeScheduleManagement = () => {
  showScheduleManagement.value = false;
};

const closeVehicleManagement = () => {
  showUnifiedFuelManagement.value = false;
};

// 生命周期钩子
onMounted(async () => {
  // 初始化认证状态
  await authStore.initAuth();
  
  // 如果已认证，获取日程数据
  if (authStore.isAuthenticated) {
    try {
      await scheduleStore.fetchSchedules();
      await familyStore.fetchFamilyMembers();
    } catch (error) {
      console.error('Failed to fetch data:', error);
    }
  }

  // 添加键盘事件监听器
  document.addEventListener("keydown", handleKeyDown);

  // 添加显示登录模态框事件监听器
  window.addEventListener("show-login-modal", handleShowLoginModal);

  // 添加认证要求事件监听器（401错误时触发）
  window.addEventListener("auth-required", handleAuthRequired);

  // 添加管理组件事件监听器
  window.addEventListener("open-family-management", handleOpenFamilyManagement);
  window.addEventListener("open-family-window", handleOpenFamilyWindow);
  window.addEventListener(
    "open-accounting-management",
    handleOpenAccountingManagement,
  );
  window.addEventListener(
    "open-schedule-management",
    handleOpenScheduleManagement,
  );
});

onUnmounted(() => {
  // 清理事件监听器
  document.removeEventListener("keydown", handleKeyDown);
  window.removeEventListener("show-login-modal", handleShowLoginModal);
  window.removeEventListener("auth-required", handleAuthRequired);
  window.removeEventListener(
    "open-family-management",
    handleOpenFamilyManagement,
  );
  window.removeEventListener("open-family-window", handleOpenFamilyWindow);
  window.removeEventListener(
    "open-accounting-management",
    handleOpenAccountingManagement,
  );
  window.removeEventListener(
    "open-schedule-management",
    handleOpenScheduleManagement,
  );
});
</script>

<template>
  <el-container class="home-container" @contextmenu="handleContextMenu">
    <!-- Main content area -->
    <el-main class="home-main">
      <el-row justify="end">
        <el-col :span="2" :offset="22">
          <UserStatus />
        </el-col>
      </el-row>
      <el-row justify="center" class="search-row">
        <el-col :span="12" :md="8" :lg="6">
          <SearchBox />
        </el-col>
      </el-row>

      <el-row class="desktop-row">
        <el-col :span="24">
          <DesktopIcons @open="handleDesktopAppClick" />
        </el-col>
      </el-row>
    </el-main>

    <!-- 应用窗口 -->
    <AppWindows ref="appWindowsRef" />

    <!-- 登录模态框 -->
    <el-dialog
      v-model="loginModal.visible"
      title="登录"
      width="400px"
      :before-close="closeLoginModal"
    >
      <LoginModal
        :visible="loginModal.visible"
        @close="closeLoginModal"
        @login-success="handleLoginSuccess"
        @show-register="openRegisterModal"
      />
    </el-dialog>

    <!-- 注册模态框 -->
    <el-dialog
      v-model="registerModal.visible"
      title="注册"
      width="400px"
      :before-close="closeRegisterModal"
    >
      <RegisterModal
        :visible="registerModal.visible"
        @close="closeRegisterModal"
        @register-success="handleRegisterSuccess"
      />
    </el-dialog>

    <!-- 家庭成员管理 -->
    <el-dialog
      v-model="showFamilyManagement"
      title="家庭成员管理"
      :width="dialogWidth"
      :before-close="closeFamilyManagement"
      :class="{ 'mobile-dialog': isMobile }"
    >
      <FamilyManagement @close="closeFamilyManagement" />
    </el-dialog>

    <!-- 记账管理 -->
    <el-dialog
      v-model="showAccountingManagement"
      title="记账管理"
      :width="dialogWidth"
      :before-close="closeAccountingManagement"
      :class="{ 'mobile-dialog': isMobile }"
    >
      <AccountingManagement @close="closeAccountingManagement" />
    </el-dialog>

    <!-- 日程管理 -->
    <el-dialog
      v-model="showScheduleManagement"
      title="日程管理"
      :width="dialogWidth"
      :before-close="closeScheduleManagement"
      :class="{ 'mobile-dialog': isMobile }"
    >
      <ScheduleManagement 
        :schedules="scheduleStore.schedules" 
        @close="closeScheduleManagement" 
      />
    </el-dialog>

    <!-- 油耗统计管理 -->
    <el-dialog
      v-model="showUnifiedFuelManagement"
      title="油耗统计"
      :width="dialogWidth"
      :before-close="closeVehicleManagement"
      :class="{ 'mobile-dialog': isMobile }"
    >
      <UnifiedFuelManagement @close="closeVehicleManagement" />
    </el-dialog>

    <!-- 右键菜单 -->
    <el-dropdown
      v-model:visible="contextMenu.visible"
      :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
      trigger="contextmenu"
      @command="handleContextMenuItemClick"
    >
      <div class="context-menu-trigger"></div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
            v-for="item in contextMenu.items"
            :key="item.id"
            :command="item"
            :disabled="item.disabled"
          >
            <el-icon v-if="item.icon === '👤'"><User /></el-icon>
            <el-icon v-else-if="item.icon === '🚪'"><SwitchButton /></el-icon>
            {{ item.label }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </el-container>
</template>

<style lang="scss" scoped>
.home-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.home-header {
  padding: 0 20px;
  border-bottom: 1px solid var(--el-border-color);
  background: var(--el-bg-color);
  display: flex;
  align-items: center;
}

.home-main {
  padding: 0;
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.search-row {
  padding: 20px;
  flex-shrink: 0;
}

.desktop-row {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.context-menu-trigger {
  position: absolute;
  width: 0;
  height: 0;
  pointer-events: none;
}

// 响应式设计
@media (max-width: 768px) {
  .search-row {
    padding: 16px;
    
    .el-col {
      span: 24;
    }
  }
  
  .desktop-row {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .search-row {
    padding: 12px;
  }
  
  .desktop-row {
    padding: 12px;
  }
}

// 移动端弹窗样式
:deep(.mobile-dialog) {
  .el-dialog {
    margin: 0 !important;
    margin-top: 10px !important;
    border-radius: var(--el-border-radius-small);
  }
  
  .el-dialog__body {
    padding: 16px;
  }
}
</style>
